const Employee = require('../models/employee');
const { StatusCodes } = require('http-status-codes');
const AppError = require('../utils/appError');

class EmployeeService {
  async createEmployee(employeeData) {
    // Check if phone already exists
    const existingEmployee = await Employee.findByPhone(employeeData.phone);
    if (existingEmployee) {
      throw new AppError('Phone number already in use', StatusCodes.BAD_REQUEST);
    }

    return await Employee.create(employeeData);
  }

  async getEmployeeById(id) {
    return await Employee.findById(id);
  }

  async getAllEmployees({ status, store_id } = {}) {
    if (status && store_id) {
      return await Employee.findByStatusAndStore(status, store_id);
    } else if (status) {
      return await Employee.findByStatus(status);
    } else if (store_id) {
      return await Employee.findByStore(store_id);
    }
    return await Employee.findAll();
  }

  async updateEmployee(id, updateData) {
    await this.getEmployeeById(id); // Verify employee exists
    
    if (updateData.phone) {
      const existingEmployee = await Employee.findByPhone(updateData.phone);
      if (existingEmployee && existingEmployee.id !== parseInt(id)) {
        throw new AppError('Phone number already in use', StatusCodes.BAD_REQUEST);
      }
    }

    return await Employee.update(id, updateData);
  }

  async deleteEmployee(id) {
    await this.getEmployeeById(id); // Verify employee exists
    return await Employee.delete(id);
  }

  async getEmployeesByStatus(status) {
    return await Employee.findByStatus(status);
  }

  async getEmployeesByStore(store_id) {
    return await Employee.findByStore(store_id);
  }

  async updateEmployeeStatus(id, status) {
    await this.getEmployeeById(id); // Verify employee exists
    return await Employee.updateStatus(id, status);
  }
}

module.exports = new EmployeeService();